public class pvv_ctlr 
{
    Public Health_Card_Renewal_Form__c Application {get; set;}
    Public String dateOfBirth {get; set;}   
    Public String passportIssueDate {get; set;}    
    Public String passportExpiryDate {get; set;}
    
    Public String SponserPassportExpiry {get; set;}   //DRV_Sponser_Passport_Expiry__c
    Public String SponserResidencyExpiry {get; set;}  //DRV_Sponser_Residency_Expiry__c
    Public String SponserDate {get; set;}             //DRV_Sponser_Date__c
    
    public static Boolean testFlag=true;
    
    Public String JobTitle {get; set;}         //Application.Job_Title_Position__c
    
    
    Public Static String WebParam {get; set;}
    
    
    public static string stdemo {get; set;}
    
    public static string url = null;
    public string geturl() { return url;}
    
    public static string soapXML = null;
    public string getsoapXML(){return soapXML;}
    
    public static string xml = null;
    public string getxml() { return xml;}    
    
    public pvv_ctlr()
    {
        Application = new Health_Card_Renewal_Form__c();
        Application.First_Name__c = 'First';
        Application.Middle_Name__c = 'Middle';
        Application.Last_Name__c = 'Last';
        
    }
    public void testFlagMark(){
       testFlag = false ;
    }
    public List<SelectOption> getCountries()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        List<Country__c> CountriesList = [SELECT id, Name FROM Country__c WHERE IsActive__c = true Order By Name];
        options.add(new SelectOption('', ''));
        for(Country__c country : CountriesList)
        {
            options.add(new SelectOption(country.id, country.name));
        }
        
        return options;
    }
    
    public List<SelectOption> getCountriesList()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        List<CountriesList__c> CountriesList = [SELECT id, Name FROM CountriesList__c WHERE IsActive__c = true Order By Name];
        options.add(new SelectOption('', ''));
        for(CountriesList__c country : CountriesList)
        {
            options.add(new SelectOption(country.id, country.name));
        }
        
        return options;
    }
    
    public List<SelectOption> getCompanies()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        List<Account> CompaniesList = [SELECT id, Name FROM Account Order By Name LIMIT 999];
        options.add(new SelectOption('', ''));
        for(Account company : CompaniesList)
        {
            options.add(new SelectOption(company.id, company.name));
        }
        
        return options;
    }
    
    public List<SelectOption> getJobTitles()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        List<Occupation__c> OccupationsList = [SELECT id, Name FROM Occupation__c WHERE IsActive__c = true Order By Name LIMIT 999];
        options.add(new SelectOption('', ''));
        for(Occupation__c occupation : OccupationsList)
        {
            options.add(new SelectOption(occupation.id, occupation.name));
        }
        
        return options;
    }
    
    //public List<SelectOption> getQualifications()
    //{
    //    List<SelectOption> options = new List<SelectOption>();
        
    //    List<Qualification__c> QualificationsList = [SELECT id, Name FROM Qualification__c WHERE IsActive__c = true Order By Name LIMIT 999];
    //    options.add(new SelectOption('', ''));
    //    for(Qualification__c qualification : QualificationsList)
    //    {
    //       options.add(new SelectOption(qualification.id, qualification.name));
    //    }
        
    //    return options;
    //}
    
    public List<SelectOption> getGenders()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        options.add(new SelectOption('Male', 'Male'));
        options.add(new SelectOption('Female', 'Female'));
        
        return options;
    }
    public List<SelectOption> getRelationSponser()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('', ''));     
        options.add(new SelectOption('Brother', 'Brother'));
        options.add(new SelectOption('Daughter', 'Daughter'));
        options.add(new SelectOption('Father', 'Father'));
        options.add(new SelectOption('Husband', 'Husband'));
        options.add(new SelectOption('Mom Husband', 'Mom Husband'));
        options.add(new SelectOption('Mother', 'Mother'));
        options.add(new SelectOption('Sister', 'Sister'));
        options.add(new SelectOption('Son', 'Son'));
        options.add(new SelectOption('Unrelated', 'Unrelated'));
        options.add(new SelectOption('Wife', 'Wife'));
        
        return options;
    }
    
    public List<SelectOption> getTitles()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        options.add(new SelectOption('Mr', 'Mr'));
        options.add(new SelectOption('Mrs', 'Mrs'));
        options.add(new SelectOption('Ms', 'Ms'));
        
        return options;
    }
    
    
    
    
    public List<SelectOption> getMaritalStatuses()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        options.add(new SelectOption('Single', 'Single'));
        options.add(new SelectOption('Married', 'Married'));
        options.add(new SelectOption('Divorced', 'Divorced'));
        options.add(new SelectOption('Widowed', 'Widowed'));
        
        return options;
    }
    
    public List<SelectOption> getReligions()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('', ''));
        options.add(new SelectOption('Bahaei', 'Bahaei'));
        options.add(new SelectOption('Budhist', 'Budhist'));
        options.add(new SelectOption('Cristian', 'Cristian'));
        options.add(new SelectOption('Hindu', 'Hindu'));
        options.add(new SelectOption('Kadiani', 'Kadiani'));
        options.add(new SelectOption('Muslim', 'Muslim'));
        options.add(new SelectOption('Sikh', 'Sikh'));
        
        return options;
    }
    
    
    
    Public PageReference ResetApplication()
    {
        Application = new Health_Card_Renewal_Form__c();
        dateOfBirth = '';   
        passportIssueDate = '';    
        passportExpiryDate = '';
        SponserPassportExpiry = '';
        SponserResidencyExpiry = '';
        SponserDate = '';
        return null;
    }
    
    Public PageReference ToMainMenu()
    {
        PageReference pg = new PageReference('/home');
        return pg;
    }
    
    public List<SelectOption> getPortOfEntries()
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('', ''));
        options.add(new SelectOption('Abu Dhabi International Airport', 'Abu Dhabi International Airport'));
        options.add(new SelectOption('Al Ain International Airport', 'Al Ain International Airport'));
        options.add(new SelectOption('Dubai International Airport', 'Dubai International Airport'));
        options.add(new SelectOption('Sharjah International Airport', 'Sharjah International Airport'));
        options.add(new SelectOption('Other', 'Other'));
        
        return options;
    }
    
    public List<SelectOption> getVisaPeriod()
    {
        List<SelectOption> options = new List<SelectOption>();
        
        options.add(new SelectOption('30 Days', '30 Days'));
        options.add(new SelectOption('90 Days', '90 Days'));
        
        return options;
    }
    public static Date stringToDate(String s){
      //XML Date String is in the format DD/MM/YYYY
      try{
          String[] stringDate = s.split('/');
          Integer d =  Integer.valueOf(stringDate[0]);
          Integer m = Integer.valueOf(stringDate[1]);
          Integer y = Integer.valueOf(stringDate[2]);
          
          if (d > 31 || m > 12 ||  y < 1800){
             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please make sure all Date values to be in DD/MM/YYYY format.'));
             return null ;
          }
          
          return date.newInstance(y,m,d);
      }catch(System.Exception er){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please make sure all Date values to be in DD/MM/YYYY format.'));
          return null ;
      }    
    }
    Public PageReference CreateApplication()
    {
        if (Application.Visa_Period__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Visa Period'));
        }
        if (Application.Port_of_Entry__c == null ){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Port of Entry'));
        }
        if (Application.Title__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Title'));
        }
        
        if (Application.First_Name__c == 'First' || Application.First_Name__c == ''){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for First Name'));
        }
        if (Application.Middle_Name__c == 'Middle'){          
           Application.Middle_Name__c = '' ;
        }
        if (Application.Last_Name__c == 'Last' || Application.Last_Name__c == ''){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Last Name'));
        }
        
        //if (Application.Arabic_Name__c == null || Application.Arabic_Name__c == ''){
        //  ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Arabic Name'));
        //}
        
        if (Application.Currently_Nationality__c == null ){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Currently Nationality'));
        }
        if (Application.Previous_Nationality__c == null ){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Previous Nationality'));
        }
        
        if (dateOfBirth== null || dateOfBirth==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Date of Birth'));
        }else{
           Application.Date_of_Birth__c = stringToDate(dateOfBirth);
        }
        
        if (Application.Country_of_Birth__c == null ){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Country of Birth'));
        }
        
        if (Application.City_of_Birth__c == null || Application.City_of_Birth__c ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose City of Birth'));
        }
        
        if (Application.Passport_Number__c == null || Application.Passport_Number__c == '' ){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Insert Passport Number'));
        }
        
        if (passportIssueDate == null || passportIssueDate ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Passport Issue Date'));
        }else{
           Application.Passport_Issue_Date__c = stringToDate(passportIssueDate);
        }
        
        if (passportExpiryDate == null || passportExpiryDate ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Passport Expiry Date'));
        }else{
           Application.Passport_Expiry_Date__c = stringToDate(passportExpiryDate);
        }
        
        if (Application.Passport_Country_of_Issue__c == null ){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Passport Country of Issue'));
        }
        
        if (Application.Passport_City_of_Issue__c == null || Application.Passport_City_of_Issue__c ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Passport City of Issue'));
        }
        
        if (Application.Mother_Full_Name__c == null || Application.Mother_Full_Name__c ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Insert Mother Full Name'));
        }
        
        if (Application.Marital_Status__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Marital Status'));
        }
        
        if (Application.Religion__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Religion'));
        }
        
        if (Application.Job_Title_Position__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Job Title/Position'));
        }
        
        if (Application.DRV_Relation_with_Sponser__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Relation With Sponser'));
        }
        
        if (Application.Gender__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Gender'));
        }
        
        
        // Validate Sponser Section
        if (Application.DRV_Sponser_Title__c == null){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Sponser Title'));
        }
        else
        {
            if(Application.DRV_Sponser_Title__c == 'Mr')
            {
                Application.Sponsor_Gender__c = 'Male';
            }
            else
            {
                Application.Sponsor_Gender__c = 'Female';
            }
        }  
        if (Application.DRV_Sponser_First_Name__c == 'First' || Application.DRV_Sponser_First_Name__c == ''){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser First Name'));
        }
        if (Application.DRV_Sponser_Middle_Name__c == 'Middle'){          
           Application.DRV_Sponser_Middle_Name__c = '' ;
        }
        if (Application.DRV_Sponser_Last_Name__c == 'Last' || Application.DRV_Sponser_Last_Name__c == ''){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Last Name'));
        }
        
        if (Application.DRV_Sponser_Currently_Nationality__c == null ){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Currently Nationality'));
        }
        
        if (Application.DRV_Sponser_Home_Phone__c == null || Application.DRV_Sponser_Home_Phone__c == ''){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Home Phone'));
        }
        
        if (Application.DRV_Sponser_Office_Phone__c == null || Application.DRV_Sponser_Office_Phone__c == ''){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Office Phone'));
        }
        
        //if (Application.DRV_Sponser_Mobile__c == null || Application.DRV_Sponser_Mobile__c == ''){
        //  ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Mobile'));
        //}
        
        if (Application.DRV_Sponser_Visa_Number_1__c == null ){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Visa Number Part 1'));
        }
        
        if (Application.DRV_Sponser_Visa_Number_2__c == null ){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Visa Number Part 1'));
        }
        
        if (Application.DRV_Sponser_Visa_Number_3__c == null ){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Visa Number Part 1'));
        }
        
        if (Application.DRV_Sponser_Passport_Number__c == null ){
          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must enter a value for Sponser Passport Number'));
        }
        
        if (SponserPassportExpiry == null || SponserPassportExpiry ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Sponser Passport Expiry'));
        }else{
           Application.DRV_Sponser_Passport_Expiry__c = stringToDate(SponserPassportExpiry);
        }
        
        if (SponserResidencyExpiry == null || SponserResidencyExpiry ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Sponser Residency Expiry'));
        }else{
           Application.DRV_Sponser_Residency_Expiry__c = stringToDate(SponserResidencyExpiry);
        }
        
        if (Application.DRV_Sponser_Company_Name__c == null ){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose Sponser Company'));
        }
        
        if (SponserDate == null || SponserDate ==  ''){
           ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Must Choose SponserCompany Date'));
        }else{
           Application.DRV_Sponser_Date__c = stringToDate(SponserDate);
        }
        if (ApexPages.hasMessages()){
           return null ;
        }
    
        try
        {
            Form_Header__c Header = [SELECT id, Name, Barcode_Type__c, (SELECT id, Name, Field_Master__c, Field_Master__r.API_Name__c, Field_Master__r.Reference_To__c, Field_Master__r.Referencing_Value__c, Position__c, Tab_Space__c, Source__c, Default_Value__c, Default_Value__r.Value__c FROM Form_Details__r order by Position__c) From Form_Header__c WHERE Name = 'Personal Visit Visa'];
            String Webservice_String = '';
            for(Form_Detail__c Detail : Header.Form_Details__r)
            {
                if(Detail.Field_Master__r.API_Name__c == NULL)
                {
                    Webservice_String += '*' + Detail.Tab_Space__c + '|';
                }
                
                    else if(Detail.Source__c == 'Form')
                    {     
                       String FieldValue = '';

                       if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Visa_Number_3__c'){
                         FieldValue = Application.DRV_Sponser_Visa_Number_3__c ;    
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_First_Name__c'){
                         FieldValue = Application.DRV_Sponser_First_Name__c ;               
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Middle_Name__c'){
                         FieldValue = Application.DRV_Sponser_Middle_Name__c ;                 
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Last_Name__c'){
                         FieldValue = Application.DRV_Sponser_Last_Name__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'Sponsor_Gender__c'){
                         FieldValue = Application.Sponsor_Gender__c;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Currently_Nationality__c'){
                         FieldValue = Application.DRV_Sponser_Currently_Nationality__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Visa_Number_2__c'){
                         FieldValue = Application.DRV_Sponser_Visa_Number_2__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Residency_Expiry__c'){
                         FieldValue = string.valueOf(Application.DRV_Sponser_Residency_Expiry__c).split('-', 0)[2] + '/' + string.valueOf(Application.DRV_Sponser_Residency_Expiry__c).split('-', 0)[1] + '/' + string.valueOf(Application.DRV_Sponser_Residency_Expiry__c).split('-', 0)[0];                  
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Passport_Number__c'){
                         FieldValue = Application.DRV_Sponser_Passport_Number__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Passport_Expiry__c'){
                         FieldValue = string.valueOf(Application.DRV_Sponser_Passport_Expiry__c).split('-', 0)[2] + '/' + string.valueOf(Application.DRV_Sponser_Passport_Expiry__c).split('-', 0)[1] + '/' + string.valueOf(Application.DRV_Sponser_Passport_Expiry__c).split('-', 0)[0];                 
                       }else if(Detail.Field_Master__r.API_Name__c == 'First_Name__c'){
                         FieldValue = Application.First_Name__c ;          
                       }else if(Detail.Field_Master__r.API_Name__c == 'Middle_Name__c'){
                         FieldValue = Application.Middle_Name__c ;         
                       }else if(Detail.Field_Master__r.API_Name__c == 'Last_Name__c'){
                         FieldValue = Application.Last_Name__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'Currently_Nationality__c'){
                         FieldValue = Application.Currently_Nationality__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'Job_Title_Position__c'){
                         FieldValue = Application.Job_Title_Position__c ;          
                       }else if(Detail.Field_Master__r.API_Name__c == 'Gender__c'){
                         FieldValue = Application.Gender__c ;              
                       }else if(Detail.Field_Master__r.API_Name__c == 'Date_of_Birth__c'){
                         FieldValue = string.valueOf(Application.Date_of_Birth__c).split('-', 0)[2] + '/' + string.valueOf(Application.Date_of_Birth__c).split('-', 0)[1] + '/' + string.valueOf(Application.Date_of_Birth__c).split('-', 0)[0];      
                       }else if(Detail.Field_Master__r.API_Name__c == 'City_of_Birth__c'){
                         FieldValue = Application.City_of_Birth__c ;                
                       }else if(Detail.Field_Master__r.API_Name__c == 'Country_of_Birth__c'){
                         FieldValue = Application.Country_of_Birth__c ;            
                       }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Number__c'){
                         FieldValue = Application.Passport_Number__c ;             
                       }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Country_of_Issue__c'){
                         FieldValue = Application.Passport_Country_of_Issue__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'Passport_City_of_Issue__c'){
                         FieldValue = Application.Passport_City_of_Issue__c ;           
                       }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Issue_Date__c'){
                         FieldValue = string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[2] + '/' + string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[1] + '/' + string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[0];   
                       }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Expiry_Date__c'){
                         FieldValue = string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[2] + '/' + string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[1] + '/' + string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[0];       
                       }else if(Detail.Field_Master__r.API_Name__c == 'Religion__c'){
                         FieldValue = String.ValueOf(Application.Religion__c)  ;   
                       }else if(Detail.Field_Master__r.API_Name__c == 'Marital_Status__c'){
                         FieldValue = String.ValueOf(Application.Marital_Status__c) ;      
                       }else if(Detail.Field_Master__r.API_Name__c == 'Previous_Nationality__c'){
                         FieldValue = String.ValueOf(Application.Previous_Nationality__c) ;    
                       }else if(Detail.Field_Master__r.API_Name__c == 'Mother_Full_Name__c'){
                         FieldValue = String.ValueOf(Application.Mother_Full_Name__c) ;    
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Mobile__c'){
                         FieldValue = Application.DRV_Sponser_Mobile__c;
                       }else if(Detail.Field_Master__r.API_Name__c == 'DRV_Relation_with_Sponser__c'){
                         FieldValue = Application.DRV_Relation_with_Sponser__c;
                       }
                        if(Detail.Field_Master__r.Reference_To__c.substring(1, Detail.Field_Master__r.Reference_To__c.length() - 1) != '')
                        {
                            string Strg = Detail.Field_Master__r.Reference_To__c.substring(1, Detail.Field_Master__r.Reference_To__c.length() - 1);
                            Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
                            Schema.SObjectType stype = gd.get(Strg);
                            sObject tagrcd;
                    
                            tagrcd = stype.newSObject();
                               if(Detail.Field_Master__r.API_Name__c == 'DRV_Sponser_Currently_Nationality__c'){ 
                                 tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.DRV_Sponser_Currently_Nationality__c + '\'');          
                               }else if(Detail.Field_Master__r.API_Name__c == 'Currently_Nationality__c'){
                                 tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Currently_Nationality__c + '\'');     
                               }else if(Detail.Field_Master__r.API_Name__c == 'Job_Title_Position__c'){
                                 tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Job_Title_Position__c + '\'');    
                               }else if(Detail.Field_Master__r.API_Name__c == 'Country_of_Birth__c'){
                                 tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Country_of_Birth__c + '\'');  
                               }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Country_of_Issue__c'){
                                 tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Passport_Country_of_Issue__c + '\'');     
                               }else if(Detail.Field_Master__r.API_Name__c == 'Previous_Nationality__c'){
                                 tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Previous_Nationality__c + '\'');          
                               }
                            
                            try
                            {
                              Webservice_String += tagrcd.get(Detail.Field_Master__r.Referencing_Value__c) + '*' + Detail.Tab_Space__c + '|';
                            }catch(System.Exception er)
                            { 
                              Webservice_String += '' +  + '*' + Detail.Tab_Space__c + '|'; 
                            }
                        }
                        else
                        {
                            if(FieldValue != null)
                            {
                                if(Detail.Field_Master__r.API_Name__c == 'Gender__c')
                                {
                                    if(FieldValue == 'Female')
                                    {
                                        Webservice_String += FieldValue + '*6|';
                                    }
                                    else
                                    {
                                        Webservice_String += FieldValue + '*' + Detail.Tab_Space__c + '|';
                                    }
                                }
                                else
                                {
                                    Webservice_String += FieldValue + '*' + Detail.Tab_Space__c + '|';
                                }
                            }else{Webservice_String += '*' + Detail.Tab_Space__c + '|';}
                        }
                    }
                    else if(Detail.Source__c == 'Constant')
                    {
                        if(Detail.Default_Value__r.Value__c != null){
                        Webservice_String += Detail.Default_Value__r.Value__c + '*' + Detail.Tab_Space__c + '|';}
                        else { Webservice_String += '*' + Detail.Tab_Space__c + '|';}
                    }
            }    
            Webservice_String += '|' + Header.Barcode_Type__c;
            
            WebParam = Webservice_String;
            GenerateBarcode();
            string tdemo1 = stdemo;
            
            Header = [SELECT id, Name, Barcode_Type__c, (SELECT id, Name, Field_Master__c, Field_Master__r.API_Name__c, Field_Master__r.Reference_To__c, Field_Master__r.Referencing_Value__c, Position__c, Tab_Space__c, Source__c, Default_Value__c, Default_Value__r.Value__c FROM Form_Details__r order by Position__c) From Form_Header__c WHERE Name = 'SAP3'];
            Webservice_String = '';
            
            for(Form_Detail__c Detail : Header.Form_Details__r)
            {
                if(Detail.Field_Master__r.API_Name__c == NULL)
                {
                    Webservice_String += '*' + Detail.Tab_Space__c + '|';
                }
                else if(Detail.Source__c == 'Form')
                    {
                        String FieldValue = '';

                        if(Detail.Field_Master__r.API_Name__c == 'Title__c'){
                          FieldValue = Application.Title__c ;   
                        }else if(Detail.Field_Master__r.API_Name__c == 'Last_Name__c'){
                          FieldValue = Application.Last_Name__c ;                
                        }else if(Detail.Field_Master__r.API_Name__c == 'Middle_Name__c'){
                          FieldValue = Application.Middle_Name__c ;              
                        }else if(Detail.Field_Master__r.API_Name__c == 'First_Name__c'){
                          FieldValue = Application.First_Name__c ;          
                        }else if(Detail.Field_Master__r.API_Name__c == 'Gender__c'){
                          FieldValue = Application.Gender__c ;          
                        }else if(Detail.Field_Master__r.API_Name__c == 'English__c'){
                          FieldValue = Application.English__c ;         
                        }else if(Detail.Field_Master__r.API_Name__c == 'Date_of_Birth__c'){
                          if(string.valueOf(Application.Date_of_Birth__c).split('-', 0)[0].Length() > 1){
                              FieldValue = string.valueOf(Application.Date_of_Birth__c).split('-', 0)[2] + '.' + string.valueOf(Application.Date_of_Birth__c).split('-', 0)[1] + '.' + string.valueOf(Application.Date_of_Birth__c).split('-', 0)[0];
                              }else{ FieldValue = string.valueOf(Application.Date_of_Birth__c).split('-', 0)[2] + '.0' + string.valueOf(Application.Date_of_Birth__c).split('-', 0)[1] + '.' + string.valueOf(Application.Date_of_Birth__c).split('-', 0)[0]; }     
                        }else if(Detail.Field_Master__r.API_Name__c == 'Marital_Status__c'){
                          if(Application.Marital_Status__c == 'Single')
                            {
                                FieldValue = Application.Marital_Status__c ;
                            }
                            else if(Application.Marital_Status__c == 'Married')
                            {
                                FieldValue = 'Marr';
                            }
                            else if(Application.Marital_Status__c == 'Widow')
                            {
                                FieldValue = 'Wid';
                            }
                            else if(Application.Marital_Status__c == 'Divorced')
                            {
                                FieldValue = 'Div';
                            }
            
                        }else if(Detail.Field_Master__r.API_Name__c == 'City_of_Birth__c'){
                          FieldValue = Application.City_of_Birth__c ;           
                        }else if(Detail.Field_Master__r.API_Name__c == 'Country_of_Birth__c'){
                          FieldValue = Application.Country_of_Birth__c ;                
                        }else if(Detail.Field_Master__r.API_Name__c == 'Religion__c'){
                          FieldValue = string.valueOf(Application.Religion__c) ;    
                        }else if(Detail.Field_Master__r.API_Name__c == 'Currently_Nationality__c'){
                          FieldValue = Application.Currently_Nationality__c ;                
                        }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Number__c'){
                          FieldValue = string.valueOf(Application.Passport_Number__c) ; 
                        }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Issue_Date__c'){
                          if(string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[0].Length() > 1){
                              FieldValue = string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[2] + '.' + string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[1] + '.' + string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[0];
                              }else{ FieldValue = string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[2] + '.0' + string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[1] + '.' + string.valueOf(Application.Passport_Issue_Date__c).split('-', 0)[0]; }             
                        }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Expiry_Date__c'){
                            if(string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[0].Length() > 1){
                              FieldValue = string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[2] + '.' + string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[1] + '.' + string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[0];
                              }else{ FieldValue = string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[2] + '.0' + string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[1] + '.' + string.valueOf(Application.Passport_Expiry_Date__c).split('-', 0)[0]; }                 
                        }else if(Detail.Field_Master__r.API_Name__c == 'Passport_City_of_Issue__c'){
                          FieldValue = string.valueOf(Application.Passport_City_of_Issue__c) ;               
                        }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Country_of_Issue__c'){
                          FieldValue = string.valueOf(Application.Passport_Country_of_Issue__c) ;                
                        }
                        
                        if(Detail.Field_Master__r.Reference_To__c.substring(1, Detail.Field_Master__r.Reference_To__c.length() - 1) != '')
                        {
                            string Strg = Detail.Field_Master__r.Reference_To__c.substring(1, Detail.Field_Master__r.Reference_To__c.length() - 1);
                            Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
                            Schema.SObjectType stype = gd.get(Strg);
                            sObject tagrcd;
                    
                            tagrcd = stype.newSObject();
                            if(Detail.Field_Master__r.API_Name__c == 'Title__c'){   
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Title__c + '\'');            
                            }else if(Detail.Field_Master__r.API_Name__c == 'Last_Name__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Last_Name__c + '\'');
                            }else if(Detail.Field_Master__r.API_Name__c == 'Middle_Name__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Middle_Name__c + '\'');
                            }else if(Detail.Field_Master__r.API_Name__c == 'First_Name__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.First_Name__c + '\'');   
                            }else if(Detail.Field_Master__r.API_Name__c == 'Gender__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Gender__c + '\'');   
                            }else if(Detail.Field_Master__r.API_Name__c == 'English__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.English__c + '\'');  
                            }else if(Detail.Field_Master__r.API_Name__c == 'Date_of_Birth__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Date_of_Birth__c + '\'');    
                            }else if(Detail.Field_Master__r.API_Name__c == 'Marital_Status__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Marital_Status__c + '\'');   
                            }else if(Detail.Field_Master__r.API_Name__c == 'City_of_Birth__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.City_of_Birth__c + '\'');    
                            }else if(Detail.Field_Master__r.API_Name__c == 'Country_of_Birth__c'){
                              tagrcd = Database.Query('SELECT id, SAP_Name__c FROM ' + Strg + ' WHERE id = \'' + Application.Country_of_Birth__c + '\''); 
                            }else if(Detail.Field_Master__r.API_Name__c == 'Religion__c'){  
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Religion__c + '\'');             
                            }else if(Detail.Field_Master__r.API_Name__c == 'Currently_Nationality__c'){
                              tagrcd = Database.Query('SELECT id, SAP_Name__c FROM ' + Strg + ' WHERE id = \'' + Application.Currently_Nationality__c + '\'');    
                            }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Number__c'){ 
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Passport_Number__c + '\'');          
                            }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Issue_Date__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Passport_Issue_Date__c + '\'');
                            }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Expiry_Date__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Passport_Expiry_Date__c + '\'');
                            }else if(Detail.Field_Master__r.API_Name__c == 'Passport_City_of_Issue__c'){
                              tagrcd = Database.Query('SELECT id, ' + Detail.Field_Master__r.Referencing_Value__c + ' FROM ' + Strg + ' WHERE id = \'' + Application.Passport_City_of_Issue__c + '\'');
                            }else if(Detail.Field_Master__r.API_Name__c == 'Passport_Country_of_Issue__c'){
                              tagrcd = Database.Query('SELECT id, SAP_Name__c FROM ' + Strg + ' WHERE id = \'' + Application.Passport_Country_of_Issue__c + '\'');
                            }
                            
                            try
                            { if(Detail.Field_Master__r.API_Name__c == 'Passport_Country_of_Issue__c' || Detail.Field_Master__r.API_Name__c == 'Country_of_Birth__c' || Detail.Field_Master__r.API_Name__c == 'Currently_Nationality__c'){Webservice_String += tagrcd.get('SAP_Name__c') + '*' + Detail.Tab_Space__c + '|';}
                              else {Webservice_String += tagrcd.get(Detail.Field_Master__r.Referencing_Value__c) + '*' + Detail.Tab_Space__c + '|';}
                            }catch(System.Exception er)
                            { 
                              Webservice_String += '' +  + '*' + Detail.Tab_Space__c + '|'; 
                            }
                        }
                        else
                        {
                            if(FieldValue != null)
                            {
                                Webservice_String += FieldValue + '*' + Detail.Tab_Space__c + '|';
                            }
                            else { Webservice_String += '*' + Detail.Tab_Space__c + '|';}
                        }
                    }
                    else if(Detail.Source__c == 'Constant')
                    {
                        if(Detail.Default_Value__r.Value__c != null){
                        Webservice_String += Detail.Default_Value__r.Value__c + '*' + Detail.Tab_Space__c + '|';}
                        else { Webservice_String += '*' + Detail.Tab_Space__c + '|';}
                    }   
            }
            
            Webservice_String += '|' + Header.Barcode_Type__c;
            
            WebParam = Webservice_String;
            GenerateBarcode();
            string tdemo3 = stdemo;
            
            insert(Application);
            
            Barcode__c br = new Barcode__c(Image_URL__c = tdemo1, Application__c = Application.id);
            Insert(br);
            
            //Barcode__c br2 = new Barcode__c(Image_URL__c = tdemo2, Application__c = Application.id);
            //Insert(br2);
            
            Barcode__c br3 = new Barcode__c(Image_URL__c = tdemo3, Application__c = Application.id);
            Insert(br3);
            
            PageReference pg = new PageReference('/apex/pvvPDF?id=' + Application.id);

            return pg;
        }
        catch(System.Exception Exp)
        {
            ApexPages.AddMessages(Exp);
            return null;
        }
    }
    
    /*public static Date stringToDate(String s){
      //XML Date String is in the format dd/mm/yyyy
      String[] stringDate = s.split('-');
      Integer m =  Integer.valueOf(stringDate[0]);
      Integer d = Integer.valueOf(stringDate[1]);
      Integer y = Integer.valueOf(stringDate[2]);
      return date.newInstance(y,m,d);
    }*/
    
    public static void Initializevariables()
    {
        // The webservice url -  Pass in the endpoint to be used using the string url 
        url = 'http://demo.smartpaperbpm.com/difc/soap_server/hellowsdl2.php';  

        soapXML = '<?xml version="1.0" encoding="ISO-8859-1"?>';
        soapXML += '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:servicename">';
        soapXML += '<SOAP-ENV:Body>';
        soapXML += '<DoSomething xmlns="urn:servicename">';
        soapXML += '<sf-parameters xmlns="">';
        soapXML += WebParam.replace(' & ', ' &amp; ') + '</sf-parameters>';
        soapXML += '</DoSomething>';
        soapXML += '</SOAP-ENV:Body>';
        soapXML += '</SOAP-ENV:Envelope>';
    }
    
    public static void GenerateBarcode()
    {    
        // Instantiate a new http object
        Http h = new Http();
              
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
        HttpRequest req = new HttpRequest();
        
        Initializevariables();
        
        req.setBody(soapXML);
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setHeader('Content-length', '510' );
        req.setHeader('Content-Type', 'text/xml; charset=ISO-8859-1');  
        req.setHeader('SOAPAction','"http://demo.smartpaperbpm.com/difc/soap_server/hellowsdl1.php#DoSomething"');
            
        if (testFlag){    
          //Commented out By Mustafa Zaidi on 9th of July 2012...(because Amazon Webservice is down)
          /*HttpResponse res = h.send(req);
          xml = res.getBody();
          XmlStreamReader reader = res.getXmlStreamReader();
          
          stdemo = readXMLResponse(reader,'Pass');*/
          HttpResponse res = h.send(req);
          xml = res.getBody();
          XmlStreamReader reader = res.getXmlStreamReader();
          
          stdemo = readXMLResponse(reader,'Pass');
        }else{
          stdemo = 'www.difc.ae';
        }  
    }
    
    public static String readXMLResponse(XmlStreamReader reader, String sxmltag)
    {
        string retValue;
        // Read through the XML
        system.debug(reader.toString());
        while(reader.hasNext()) 
        {
            if (reader.getEventType() == XmlTag.START_ELEMENT) 
            {
                if (reader.getLocalName() == sxmltag) 
                {
                    reader.next();
                    if (reader.getEventType() == XmlTag.characters) 
                    {
                        retValue = reader.getText();    
                    }
                } 
            }
            reader.next();
        } 
        return retValue;
    }
    
}